package com.cai.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.cai.dao.PermissionDao;
import com.cai.dao.RoleDao;
import com.cai.dao.UserDao;
import com.cai.entity.PageResult;
import com.cai.entity.QueryPageBean;
import com.cai.pojo.Permission;
import com.cai.pojo.Role;
import com.cai.pojo.User;
import com.cai.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    public void add(User user, Integer[] roleIds) {
        //先添加t_user表
        String password = user.getPassword();
        if(password!=null&&password.length()>0){
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            String encode = bCryptPasswordEncoder.encode(password);
            user.setPassword(encode);
        }
        userDao.add(user);
        //添加中间表关系
        setUserAndRole(user.getId(),roleIds);
    }
    public void delete(Integer id) {
        //先判断是否关联角色,如果关联角色需要先删除关联
        List<Integer> list = userDao.findRoleIdsByUserId(id);
        if(list!=null&&list.size()>0){
            userDao.deleteAssociation(id);
        }
        userDao.delete(id);
    }
    public User findUserById(Integer id) {
        User userById = userDao.findUserById(id);
        userById.setPassword("");
        return userById;
    }

    public List<Integer> findRoleIdsByUserId(Integer id) {

        return userDao.findRoleIdsByUserId(id);
    }
    public void edit(User user, Integer[] roleIds) {
       //先根据user_id清除中间表
        userDao.deleteAssociation(user.getId());
        //更新t_user表
        String password = user.getPassword();
        if(password!=null&&password.length()>0){
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            String encode = bCryptPasswordEncoder.encode(password);
            user.setPassword(encode);
        }
        userDao.edit(user);
        //更新中间表
        setUserAndRole(user.getId(),roleIds);

    }
    public User findUserByUsername(String username) {
        User user = userDao.findByUsername(username);
        List<Integer> roleIds = userDao.findRoleIdsByUserId(user.getId());
        Set roleSet=new HashSet();
        for (Integer roleId : roleIds) {
             Role role= roleDao.findRoleById(roleId);
             roleSet.add(role);
           List<Integer>permissionIds=roleDao.findPermissionIdsByRoleId(role.getId());
           Set<Permission>permissionSet=new HashSet<>();
            for (Integer permissionId : permissionIds) {
           Permission permission=permissionDao.findPermissionById(permissionId);
           permissionSet.add(permission);
            }
        }
        user.setRoles(roleSet);
        return user;
    }

    //分页查询
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //使用分页助手
        PageHelper.startPage(currentPage, pageSize);
        Page<User> page =userDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<User> rows = page.getResult();
        return new PageResult(total, rows);

    }
    //定义方法用于建立中间表关联
    public void setUserAndRole(Integer userId ,Integer[] roelIds) {
        if (roelIds != null && roelIds.length > 0) {
            for (Integer roleId : roelIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("user_id",userId);
                map.put("role_id", roleId);
                userDao.setUserAndRole(map);
            }
        }
    }

   /* @Test
    public void test01(){
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode("1124");
        System.out.println(encode);
    }*/
}
